package org.jeecg.modules.gather.wkhtmltopdf;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.*;

@Component
@Slf4j
public class WkHtmlToPdfUtil {
    public static boolean convert(String htmlFilePath, String pdfFilePath) {
        Process process = null;
        BufferedReader errorReader = null;

        String[] command = getCommand(htmlFilePath, pdfFilePath);

        try {
            ProcessBuilder processBuilder = new ProcessBuilder(command);
            process = processBuilder.start();
            // 捕获错误信息
            errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream()));
            StringBuilder errorMsg = new StringBuilder();
            String line;
            while ((line = errorReader.readLine()) != null) {
                errorMsg.append(line).append("\n");
            }

            int exitCode = process.waitFor();
            if (exitCode != 0) {
                log.error("Conversion failed. Error:\n{}", errorMsg);
                return false;
            }
            return true;
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
            return false;
        } finally {
            try {
                if (errorReader != null) errorReader.close();
                if (process != null) process.destroy();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private static String[] getCommand(String htmlFilePath, String pdfFilePath) {
        String safeHtmlPath = htmlFilePath.contains(" ") ? "\"" + htmlFilePath + "\"" : htmlFilePath;
        String safePdfPath = pdfFilePath.contains(" ") ? "\"" + pdfFilePath + "\"" : pdfFilePath;

        // 构建命令和选项
        return new String[]{
                getWkhtmltopdfCommand(),
                "--enable-local-file-access",
                "--no-stop-slow-scripts",
                "--load-error-handling", "ignore",
                "--page-size", "A4",
                "--orientation", "Portrait",
                "--margin-top", "20mm",
                "--margin-bottom", "20mm",
                "--margin-left", "10mm",
                "--margin-right", "10mm",
                "--encoding", "UTF-8",
                safeHtmlPath,
                safePdfPath
        };
    }

    private static String getWkhtmltopdfCommand() {
        String osName = System.getProperty("os.name").toLowerCase();
        if (osName.contains("win")) {
            return "wkhtmltopdf.exe";
        } else if (osName.contains("nix") || osName.contains("nux") || osName.contains("mac")) {
            return "wkhtmltopdf";
        }
        throw new UnsupportedOperationException("Unsupported operating system: " + osName);
    }
}
